<template>
  <div class="order-statistics">
    <h1>订单统计分析</h1>
    
    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            @change="handleDateChange">
          </el-date-picker>
        </el-form-item>
        
        <el-form-item label="商家">
          <el-select v-model="filterForm.merchantId" placeholder="选择商家" clearable @change="getStatisticsData">
            <el-option v-for="item in merchants" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="getStatisticsData">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 统计数据卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-title">总订单量</div>
          <div class="card-value">{{ statisticsData.totalCount || 0 }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-title">总交易额</div>
          <div class="card-value">{{ formatPrice(statisticsData.totalAmount) }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-title">订单均价</div>
          <div class="card-value">{{ formatPrice(statisticsData.avgAmount) }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-title">完成率</div>
          <div class="card-value">{{ getCompletionRate() }}%</div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 订单状态分布 -->
    <el-row :gutter="20" class="stats-charts">
      <el-col :span="12">
        <el-card class="chart-card" v-loading="loading">
          <div slot="header" class="chart-header">
            <span>订单状态分布</span>
          </div>
          <div id="status-pie-chart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card" v-loading="loading">
          <div slot="header" class="chart-header">
            <span>订单趋势</span>
          </div>
          <div id="trend-chart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 详细状态数据 -->
    <el-card class="status-card">
      <div slot="header" class="status-card-header">
        <span>订单状态详情</span>
      </div>
      
      <el-table :data="statusTableData" style="width: 100%">
        <el-table-column prop="name" label="状态"></el-table-column>
        <el-table-column prop="count" label="数量"></el-table-column>
        <el-table-column prop="percentage" label="占比">
          <template slot-scope="scope">
            {{ scope.row.percentage }}%
          </template>
        </el-table-column>
        <el-table-column label="可视化" width="300">
          <template slot-scope="scope">
            <el-progress :percentage="scope.row.percentage" :color="scope.row.color"></el-progress>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 热门商家排行 -->
    <el-card class="merchant-card" v-if="!filterForm.merchantId">
      <div slot="header" class="merchant-card-header">
        <span>热门商家排行</span>
      </div>
      
      <el-table :data="merchantRanking" style="width: 100%">
        <el-table-column label="排名" width="80">
          <template slot-scope="scope">
            <div class="ranking">{{ scope.$index + 1 }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商家名称"></el-table-column>
        <el-table-column prop="orderCount" label="订单量"></el-table-column>
        <el-table-column prop="orderAmount" label="交易额">
          <template slot-scope="scope">
            {{ formatPrice(scope.row.orderAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="交易占比" width="300">
          <template slot-scope="scope">
            <el-progress :percentage="scope.row.percentage" :color="scope.row.color"></el-progress>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { getOrderStatistics, getOrderMerchants, getOrderMerchantRanking } from '@/api/admin';
import * as echarts from 'echarts';

export default {
  name: 'OrderStatistics',
  data() {
    return {
      filterForm: {
        dateRange: [],
        merchantId: null
      },
      loading: false,
      statisticsData: {
        totalCount: 0,
        totalAmount: 0,
        avgAmount: 0,
        statusCounts: {}
      },
      merchants: [],
      statusColors: {
        pending: '#909399',
        waiting: '#E6A23C',
        inProgress: '#409EFF',
        completed: '#67C23A',
        canceled: '#F56C6C'
      },
      statusMap: {
        pending: '待支付',
        waiting: '待接单',
        inProgress: '配送中',
        completed: '已完成',
        canceled: '已取消'
      },
      statusChart: null,
      trendChart: null,
      merchantRanking: []
    };
  },
  computed: {
    // 状态表格数据
    statusTableData() {
      const { statusCounts } = this.statisticsData;
      const totalCount = this.statisticsData.totalCount || 0;
      
      if (!statusCounts || totalCount === 0) return [];
      
      return Object.keys(this.statusMap).map(key => {
        const count = statusCounts[key] || 0;
        const percentage = totalCount > 0 ? Math.round((count / totalCount) * 100 * 100) / 100 : 0;
        
        return {
          name: this.statusMap[key],
          count,
          percentage,
          color: this.statusColors[key]
        };
      });
    }
  },
  created() {
    this.initDates();
    this.getMerchantList();
    this.getStatisticsData();
  },
  mounted() {
    this.initCharts();
    // 添加窗口大小变化监听
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.statusChart) {
      this.statusChart.dispose();
      this.statusChart = null;
    }
    if (this.trendChart) {
      this.trendChart.dispose();
      this.trendChart = null;
    }
    // 移除窗口大小变化监听器
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    // 初始化图表
    initCharts() {
      this.$nextTick(() => {
        // 初始化前先检查DOM元素是否存在
        if (document.getElementById('status-pie-chart') && document.getElementById('trend-chart')) {
          this.statusChart = echarts.init(document.getElementById('status-pie-chart'));
          this.trendChart = echarts.init(document.getElementById('trend-chart'));
          
          // 立即渲染初始图表
          if (this.statisticsData && this.statisticsData.statusCounts) {
            this.updateStatusChart();
          }
          if (this.statisticsData && this.statisticsData.trends) {
            this.updateTrendChart();
          }
        } else {
          // 如果DOM元素不存在，延迟再次尝试初始化
          setTimeout(() => {
            this.initCharts();
          }, 300);
        }
      });
    },
    
    // 处理窗口大小改变
    handleResize() {
      if (this.statusChart) {
        this.statusChart.resize();
      }
      if (this.trendChart) {
        this.trendChart.resize();
      }
    },
    
    // 获取统计数据
    getStatisticsData() {
      this.loading = true;
      
      const params = {};
      
      if (this.filterForm.dateRange && this.filterForm.dateRange.length === 2) {
        params.startDate = this.filterForm.dateRange[0];
        params.endDate = this.filterForm.dateRange[1];
      }
      
      if (this.filterForm.merchantId) {
        params.merchantId = this.filterForm.merchantId;
      }
      
      getOrderStatistics(params).then(res => {
        if (res.code === 200) {
          this.statisticsData = res.data;
          this.updateCharts();
          this.generateMerchantRanking();
        } else {
          this.$message.error(res.message || '获取统计数据失败');
        }
      }).catch(err => {
        console.error('获取统计数据失败', err);
        this.$message.error('获取统计数据失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 更新图表数据
    updateCharts() {
      this.updateStatusChart();
      this.updateTrendChart();
    },
    
    // 更新状态饼图
    updateStatusChart() {
      const { statusCounts } = this.statisticsData;
      
      if (!statusCounts || !this.statusChart) return;
      
      // 转换数据为图表所需格式
      const pieData = Object.keys(this.statusMap).map(key => ({
        name: this.statusMap[key],
        value: statusCounts[key] || 0,
        itemStyle: {
          color: this.statusColors[key]
        }
      })).filter(item => item.value > 0); // 过滤掉值为0的项，避免空白扇区
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: Object.values(this.statusMap)
        },
        series: [
          {
            name: '订单状态',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              formatter: '{b}: {c} ({d}%)',
              fontSize: 12
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 14,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: true
            },
            data: pieData,
            animationType: 'scale',
            animationEasing: 'elasticOut'
          }
        ]
      };
      
      try {
        this.statusChart.setOption(option);
        this.statusChart.resize();
      } catch (error) {
        console.error('更新状态饼图失败:', error);
        // 尝试重新初始化图表
        this.$nextTick(() => {
          this.initCharts();
          setTimeout(() => {
            if (this.statusChart) {
              this.statusChart.setOption(option);
            }
          }, 300);
        });
      }
    },
    
    // 更新趋势图
    updateTrendChart() {
      const { trends } = this.statisticsData;
      
      if (!trends || !this.trendChart) return;
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          },
          formatter: function(params) {
            let result = params[0].name + '<br/>';
            params.forEach(param => {
              const valueText = param.seriesName === '交易额' 
                ? '¥' + param.value.toFixed(2) 
                : param.value;
              result += param.marker + ' ' + param.seriesName + ': ' + valueText + '<br/>';
            });
            return result;
          }
        },
        legend: {
          data: ['订单量', '交易额']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '8%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: trends.labels || [],
            axisLabel: {
              rotate: 30,
              interval: 'auto'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '订单量',
            position: 'left',
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '交易额',
            position: 'right',
            axisLabel: {
              formatter: '¥{value}'
            }
          }
        ],
        series: [
          {
            name: '订单量',
            type: 'line',
            stack: '总量',
            areaStyle: {
              opacity: 0.3
            },
            data: trends.orderCounts || [],
            smooth: true,
            symbolSize: 6,
            lineStyle: {
              width: 2
            }
          },
          {
            name: '交易额',
            type: 'line',
            stack: '总额',
            areaStyle: {
              opacity: 0.3
            },
            yAxisIndex: 1,
            data: trends.orderAmounts || [],
            smooth: true,
            symbolSize: 6,
            lineStyle: {
              width: 2
            }
          }
        ],
        color: ['#409EFF', '#67C23A']
      };
      
      try {
        this.trendChart.setOption(option);
        this.trendChart.resize();
      } catch (error) {
        console.error('更新趋势图失败:', error);
        // 尝试重新初始化图表
        this.$nextTick(() => {
          this.initCharts();
          setTimeout(() => {
            if (this.trendChart) {
              this.trendChart.setOption(option);
            }
          }, 300);
        });
      }
    },
    
    // 获取商家列表
    getMerchantList() {
      this.loading = true;
      getOrderMerchants().then(res => {
        if (res.code === 200) {
          this.merchants = res.data || [];
        } else {
          this.$message.error(res.message || '获取商家列表失败');
        }
      }).catch(err => {
        console.error('获取商家列表失败', err);
        this.$message.error('获取商家列表失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 生成商家排行数据
    generateMerchantRanking() {
      if (this.filterForm.merchantId) {
        this.merchantRanking = [];
        return;
      }
      
      getOrderMerchantRanking(this.filterForm).then(res => {
        if (res.code === 200) {
          this.merchantRanking = res.data || [];
        } else {
          this.generateMockMerchantRanking();
        }
      }).catch(() => {
        this.generateMockMerchantRanking();
      });
    },
    
    // 生成模拟商家排行数据（仅在API失败时使用）
    generateMockMerchantRanking() {
      const colors = ['#f56c6c', '#e6a23c', '#409eff', '#67c23a', '#909399'];
      const totalAmount = this.statisticsData.totalAmount || 1000;
      
      this.merchantRanking = this.merchants.map((merchant, index) => {
        const orderCount = Math.floor(Math.random() * 100) + 20;
        const orderAmount = Math.floor(Math.random() * 10000) + 1000;
        const percentage = Math.round((orderAmount / totalAmount) * 100);
        
        return {
          ...merchant,
          orderCount,
          orderAmount,
          percentage: percentage > 100 ? 100 : percentage,
          color: colors[index % colors.length]
        };
      }).sort((a, b) => b.orderAmount - a.orderAmount);
    },
    
    // 处理日期变化
    handleDateChange() {
      this.getStatisticsData();
    },
    
    // 重置表单
    resetForm() {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 7 * 24 * 60 * 60 * 1000);
      
      this.filterForm = {
        dateRange: [
          this.formatDate(start),
          this.formatDate(end)
        ],
        merchantId: null
      };
      
      this.getStatisticsData();
    },
    
    // 格式化价格
    formatPrice(price) {
      if (price === undefined || price === null) return '¥0.00';
      return '¥' + parseFloat(price).toFixed(2);
    },
    
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 计算完成率
    getCompletionRate() {
      const { statusCounts, totalCount } = this.statisticsData;
      
      if (!statusCounts || !totalCount || totalCount === 0) return 0;
      
      const completedCount = statusCounts.completed || 0;
      return Math.round((completedCount / totalCount) * 100 * 100) / 100;
    },
    
    // 初始化默认日期
    initDates() {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 7 * 24 * 60 * 60 * 1000);
      
      this.filterForm.dateRange = [
        this.formatDate(start),
        this.formatDate(end)
      ];
    }
  }
};
</script>

<style scoped>
.order-statistics {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  align-items: center;
}

.stats-cards {
  margin-bottom: 20px;
}

.data-card {
  height: 100px;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.stats-charts {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 350px;
  width: 100%;
}

.status-card {
  margin-bottom: 20px;
}

.status-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.merchant-card {
  margin-bottom: 20px;
}

.merchant-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ranking {
  background-color: #f2f2f2;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
}

.ranking:nth-child(1) {
  background-color: #f56c6c;
  color: white;
}
</style> 